//
//  MediaBook.m
//  Dolphin
//
//  Created by Handymood on 11-5-22.
//  Copyright 2011 __Hanydmood__. All rights reserved.
//

#import "MediaBook.h"

@implementation MediaBook

@synthesize preOrientation;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) 
    {
        // Initialization code
        screen_direction = 0;
        fit_with_screen = TRUE;
        fit_page_size = FALSE;
        
        discrete_count = 0;
        cur_index = 0;
        
        previous_scroll_pos = 0.0f;
        avg_distance = 0.0f;

        auto_play_tick_count = -1000000000;
        auto_play_tick_limit = 0;

        scroll_block_signal = FALSE;
        
        bar_status_hidden = TRUE;
        
        slide_play_on_stack = FALSE;
        slide_bgm_on_stack = FALSE;
        
        webLayerOn = FALSE;
        categoryOn = FALSE;
        
        preOrientation = 0;
        pages = [[NSMutableSet alloc] init];
        tempMediaSet = [[NSMutableSet alloc] init];
        
        bookXMLParser = [[MediaBookXMLParser alloc] init];
        albumXMLParser = [[AlbumXMLParser alloc] init];
    }
    return self;
}

//global data configuration
-(void) initWithGlobalSet:(GlobalSet *) inGlobalSet
{
    if (!inGlobalSet.fullscreen_mode) 
    {
        bookXMLParser.upToolBarInfo.twitter_link = @"";
        bookXMLParser.upToolBarInfo.facebook_link = @"";
        bookXMLParser.upToolBarInfo.home_link = @"";
        
        gDataSet.align = @"v";
    }
    
    gDataSet = inGlobalSet;
    page_width = inGlobalSet.page_width;
    page_height = inGlobalSet.page_height;
    active_page_num = inGlobalSet.active_page_num;
    active_page_range = round((active_page_num-1)/2);
    
    NSLog(@"active_page_range%d",active_page_range);
    
    fit_with_screen = inGlobalSet.fit_with_screen;
   
    if(inGlobalSet.status_bar_hidden)
    {
        status_bar_hidden = TRUE;
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
    else
    {
        status_bar_hidden = FALSE;    
    }
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect
 {
 // Drawing code
 }
 */

-(void) initBook:(NSString *) configXmlAdd
                suffix:(NSString *) inSuffix
  curOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    //start loading icon
    CGRect screen_rect = [[UIScreen mainScreen] bounds];
    
    activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    
    if(interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        activityIndicator.frame = CGRectMake(screen_rect.size.width/2-20, screen_rect.size.height/2-20, 40.0, 40.0);
    }
    else
    {
       activityIndicator.frame = CGRectMake(screen_rect.size.height/2-20, screen_rect.size.width/2-20, 40.0, 40.0);   
    }
    
    [activityIndicator startAnimating];
    [self addSubview:activityIndicator];
    
    loadOverMsg = [[NSString alloc] initWithFormat:@"load_book_xml_over%@",inSuffix];
    
    //global event listener
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:loadOverMsg object:Nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:@"load_album_xml_over" object:Nil];
    
    //xml parser start loading
    preOrientation = interfaceOrientation;
    [bookXMLParser startParsing:configXmlAdd finishMsg:loadOverMsg];
}

//load xml over, do book init
-(void) initBookContent
{    
    [bookXMLParser makeDataCompatibleWithIPhone];

    //config the page num
    page_num = bookXMLParser.gDataSet.page_num;
    
    //init the global enviroment set
    [self initWithGlobalSet:bookXMLParser.gDataSet];
        
    //init the book's frame
    if (fit_with_screen && bookXMLParser.gDataSet.fullscreen_mode) //if fit the screen,define size data with screen size
    {
        CGRect screen_rect = [[UIScreen mainScreen] bounds];
        
        int status_bar_height = 0;
        if(![UIApplication sharedApplication].statusBarHidden)
        {
            status_bar_height = 20;
        }
        
        page_width = screen_rect.size.width;
        page_height = screen_rect.size.height - status_bar_height;
    }
    
    self.frame = CGRectMake(0, 0, page_width, page_height);
    
    //set back ground color
    self.backgroundColor =  [UIColor clearColor];// [ColorUtil stringHexToUIColor:bookXMLParser.gDataSet.bg_color];
    
    //set back ground color
    bgView = [[UIView alloc] initWithFrame:self.frame];
    bgView.backgroundColor = [UIColor clearColor];//[ColorUtil stringHexToUIColor:bookXMLParser.gDataSet.bg_color];
    //[self addSubview:bgView];
    
    //init the background
    backGroundImage =[[UIImageLayer alloc] init];
    [backGroundImage initImage:bookXMLParser.gDataSet.bg_img useOriginalSize:YES ratioMode:0 layerInfo:Nil]; 
    //[self addSubview:backGroundImage];
    
    //init the main scroll view
    scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0,page_width, page_height)];
    scrollView.contentSize = CGSizeMake(page_num*page_width,page_height);
    scrollView.bounces = FALSE;
    //scrollView.scrollEnabled = FALSE;
    [scrollView setPagingEnabled:YES];
    [scrollView setShowsHorizontalScrollIndicator:NO];    
    [self addSubview:scrollView];
    
    //enable scroll interactive
    scrollView.delegate = self;
    scrollView.delaysContentTouches = YES;
    
    //create the top bar
    topBar = [[TopBar alloc] initWithFrame:CGRectMake(0, 0, page_width,bookXMLParser.upToolBarInfo.height)];
    //add sound control button
    if([bookXMLParser.gDataSet.bg_snd_link length]>4)
    {
        [topBar addAudio:bookXMLParser.gDataSet.bg_snd_link autoPlayAtInit:bookXMLParser.gDataSet.bg_snd_play_at_init];
    }
    
    //add auto play button
    if (bookXMLParser.gDataSet.auto_play_on) 
    {
        [topBar addSlideshowPlayButton:bookXMLParser.gDataSet.auto_play_at_init];
    }

    [topBar initWithToolBarInfo:bookXMLParser.upToolBarInfo];
    //[self addSubview:topBar];
    
    if (!bookXMLParser.upToolBarInfo.visible) 
    {
        topBar.hidden = TRUE;
    }
    
    //init the page index scroll view
    bottomBar = [[BottomBar alloc] initWithFrame:CGRectMake(0,page_height-bookXMLParser.bottomIndexPage.unit_height, 
                                                            page_width,bookXMLParser.bottomIndexPage.unit_height)];
    [bottomBar initWithIndexInfo:bookXMLParser.bottomIndexPage];
    //[self addSubview:bottomBar];
    
    if (!bookXMLParser.bottomIndexPage.visible) 
    {
        bottomBar.hidden = TRUE;
    }
    
    //inner web page pop up
    webLayer = [[DolphinUIWebLayer alloc] initWithFrame:CGRectMake(0,page_height,page_width, page_height)];
    webLayer.alpha = 0;
    [self addSubview:webLayer];
    
    categoryLayer = [[DolphinUICategory alloc] initWithFrame:CGRectMake(0, page_height+topBar.frame.size.height, page_width, 
                                  page_height-topBar.frame.size.height-bottomBar.frame.size.height)];
    categoryLayer.alpha = 0;
    categoryLayer.hidden = TRUE;
    [self addSubview:categoryLayer];
    
    //init with album list
    if (gDataSet.albumListPath != Nil) 
    {
        [albumXMLParser startParsing:gDataSet.albumListPath];
    }
    
    bar_status_hidden = bookXMLParser.gDataSet.show_toolbar_at_init;
    [self statusBarAnimationTrigger];
    
    //init the object management queue and recycle queue
    genNodeQueue = [[NSMutableArray alloc] init];
    recycleSet = [[NSMutableSet alloc] init];
    
    //init the first pages
    [self updateBook:0];
    
    //init the management queue
    float kTimerInternal = 0.2f;//0.075f;
    objQueMagTimer = [NSTimer scheduledTimerWithTimeInterval: kTimerInternal target:self selector:@selector(objectManageProc) userInfo:nil repeats:YES]; 
    
    //init autoplay tick
    if (bookXMLParser.gDataSet.auto_play_at_init)
    {
        on_auto_play = TRUE;
        auto_play_tick_count = 0;
    }
    else
    {
        on_auto_play = FALSE;
        auto_play_tick_count = -1000000000;
    }
    auto_play_tick_limit = bookXMLParser.gDataSet.auto_play_time_tick/kTimerInternal;

    //stop loading icon
    if(activityIndicator)
    {
        [activityIndicator stopAnimating];
    }
    
    //msg panel
    msgPanel = [[MsgPanel alloc] initWithFrame:CGRectMake(0, 0, 130, 130)];
    msgPanel.alpha = 0;
    [self addSubview:msgPanel];
    
    //the ui sheet
    theActionSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Save to Photo" otherButtonTitles:nil, nil];
    //[theActionSheet showInView:self];
    
    currentTime = 0.0f;
    previousTime = 0.0f;
    
    previousNode = 0;
    
    [self layoutAdjustWithOrientation:preOrientation orientaionType:gDataSet.align];
    
    //global event listener
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:@"img_single_tap" object:Nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:@"page_id_trigger" object:Nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:@"slide_show_play" object:Nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:@"slide_show_pause" object:Nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:@"tool_bar_show" object:Nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:@"tool_bar_hide" object:Nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:@"manually_pause_slideshow" object:Nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:@"manually_mute_bgm" object:Nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:@"manually_open_bgm" object:Nil];    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:@"open_link" object:Nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:@"close_link" object:Nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:@"show_category" object:Nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:@"category_unit_init" object:Nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:@"album_trigger" object:Nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:@"share_button_trigger"  object:Nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:@"pre_page_trigger" object:Nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:@"next_page_trigger" object:Nil];
}

//global event listeners
//for single tap on image
-(void) notificationSelector:(NSNotification *) notification
{
    NSString *curNotificationName = [notification name];
    
    if ([curNotificationName isEqualToString:loadOverMsg])
    {
        //book xml load over,generate the book
        [self initBookContent];
    }
    else if([curNotificationName isEqualToString:@"load_album_xml_over"])
    {
        [topBar displayAlbumBtn];
        categoryLayer.hidden = FALSE;
        [categoryLayer initWithAlbumList:albumXMLParser orientation:preOrientation];
    }
    else if ([curNotificationName isEqualToString:@"img_single_tap"]) 
    {
        //for image tap, bottom and topbar auto hide/display 
    }
    else if ([curNotificationName isEqualToString:@"tool_bar_show"]) 
    {
        if (bar_status_hidden == TRUE)
        {
            [UIView transitionWithView:bottomBar duration:0.35f 
                               options:UIViewAnimationCurveEaseOut  animations:^{[self statusBarAnimationTrigger];}
                            completion:NULL];
        }
    }
    else if ([curNotificationName isEqualToString:@"tool_bar_hide"]) 
    {
        /*
        if (bar_status_hidden == FALSE)
        {
            [UIView transitionWithView:bottomBar duration:1.0f 
                               options:UIViewAnimationCurveEaseOut  animations:^{[self statusBarAnimationTrigger];}
                            completion:NULL]; 
        }
         */
    }
    else  if([curNotificationName isEqualToString:@"page_id_trigger"])
    {
        UIImageLayer *tempBtn =  [notification object];
        
        currentTime = CACurrentMediaTime();
        
        //for image tap, bottom and topbar auto hide/display 
        BOOL specialJudge = FALSE;
        NSLog(@"###########");
        if (tempBtn != Nil && tempBtn.button_id>=0 && tempBtn.button_id <= 9 && !specialJudge)
        {
            if (currentTime-previousTime>0.1)
            {
                NSLog(@"*******%d %d ",tempBtn.button_id, page_num);
                if (tempBtn != Nil && tempBtn.button_id>=0 )//&& tempBtn.button_id<= page_num) 
                {
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"PAGE_ID" object:tempBtn];
                    previousTime = currentTime;
                }
            }
        }
        /*
        else  if (tempBtn != Nil && tempBtn.button_id>=0 && tempBtn.button_id< page_num && tempBtn.button_id != cur_index) 
        {
            int target_id = tempBtn.button_id;
            
            SinglePage *tmpPage = [self getPageById: target_id];
            
            if (tmpPage != Nil) 
            {
                tmpPage.alpha = 0.0f;
            }
            
            [scrollView setContentOffset:CGPointMake(target_id*page_width, 0) animated:NO];
            auto_play_tick_count = 0;
            
            [self updateSlideshowAutoPlay:target_id];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"INNTER_SHIFT" object:tempBtn];
        }
        */
        previousNode = tempBtn.button_id;
        
        /*
        if (previousNode == 14) 
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"6i4" object:tempBtn];
        }
         */
    }
    else  if([curNotificationName isEqualToString:@"slide_show_play"])
    {
        on_auto_play = TRUE;
        auto_play_tick_count = 0;
    }
    else  if([curNotificationName isEqualToString:@"slide_show_pause"])
    {
        on_auto_play = FALSE;
        auto_play_tick_count = -1000000000;
    }
    else if([curNotificationName isEqualToString:@"manually_pause_slideshow" ])
    {
        on_auto_play = FALSE;
        auto_play_tick_count = -1000000000;
    }
    else if([curNotificationName isEqualToString:@"manually_mute_bgm" ])
    { 
        if([topBar musicOn])//&&tmpPage.hasMedia)
        {
            [topBar manuallyMusicOff];
        }
    }
    else if([curNotificationName isEqualToString:@"manually_open_bgm"])
    {
        [topBar manuallyMusicOn];
    }
    else if([curNotificationName isEqualToString:@"open_link"])
    {
        [self shiftToPageId:0];
        return;
        
        webLayerOn = TRUE;
        [webLayer refreshPage : topBar.cur_link];
        webLayer.alpha = 1.0f;
        [UIView transitionWithView:webLayer duration:0.35f 
                           options:UIViewAnimationCurveEaseOut  
                        animations:^{webLayer.transform = CGAffineTransformMakeTranslation(0, -webLayer.frame.size.height);}
                        completion:NULL];
    }
    else if([curNotificationName isEqualToString:@"show_category"])
    { 
        [bottomBar visibleExchange];
        /*
        if (categoryOn) 
        {
            [self closeCategoryLayer];
            categoryOn = FALSE;
        }
        else
        {
            categoryOn = TRUE;
            
            categoryLayer.alpha = 1.0f;
            [categoryLayer refreshPage];
            [UIView transitionWithView:categoryLayer duration:0.35f 
                               options:UIViewAnimationCurveEaseOut  
                            animations:^{categoryLayer.transform = CGAffineTransformMakeTranslation(0, -categoryLayer.frame.size.height);}
                            completion:NULL];
        }
         */
    }
    else if([curNotificationName isEqualToString:@"close_link"])
    {
        webLayerOn = FALSE;
        [UIView transitionWithView:webLayer duration:0.35f 
                           options:UIViewAnimationCurveEaseOut  
                        animations:^{webLayer.transform = CGAffineTransformMakeTranslation(0,0);}
                        completion:NULL];
    }
    else if([curNotificationName isEqualToString:@"hide_category"])
    {
        [self closeCategoryLayer];
    }
    else if([curNotificationName isEqualToString:@"category_unit_init" ])
    {
        UICategoryUnit *unit =  [notification object];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"update_slideshow" object:[[NSString alloc] initWithString:unit.albumPath]];
    }
    else if([curNotificationName isEqualToString:@"album_trigger" ])
    {
        UIImageLayer *tempBtn =  [notification object];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"update_slideshow" object:[[NSString alloc] initWithString:tempBtn.target_album_xml]];
    }
    else if([curNotificationName isEqualToString:@"share_button_trigger" ])
    {
        if ([IPhone_IPad_Judge isIPad]) 
        {
            if([curOrientationView isEqualToString: @"v"])
            {
                [theActionSheet showFromRect:CGRectMake(150, 0, 0, 50) inView:self animated:YES];
            }
            else if([curOrientationView isEqualToString: @"h"])
            {
                [theActionSheet showFromRect:CGRectMake(150, 0, 0, 50) inView:self animated:YES];
            }
        }
        else
        {
            [theActionSheet showInView:self];
        }

    }
    else if([curNotificationName isEqualToString:@"pre_page_trigger"])
    {
        [self shiftToPre];
    }
    else if([curNotificationName isEqualToString:@"next_page_trigger"])
    {
        [self shiftToNext];
    }
}

-(void) shiftToPageId:(int) inId
{
    if (inId >=0 && inId< page_num && inId != cur_index) 
    {
        int target_id = inId;
        
        SinglePage *tmpPage = [self getPageById: target_id];
        
        if (tmpPage != Nil) 
        {
           // tmpPage.alpha = 0.0f;
        }
        
        [scrollView setContentOffset:CGPointMake(target_id*page_width, 0) animated:NO];
        auto_play_tick_count = 0;
        
        [self updateSlideshowAutoPlay:target_id];
    }

}

-(void) shiftToPre
{
    if (cur_index>0) 
    {
        [self shiftToPageId:cur_index-1];
    }
}

-(void) shiftToNext
{
    if (cur_index<page_num) 
    {
        [self shiftToPageId:cur_index+1];
    }
}


-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *buttonTitle = [actionSheet buttonTitleAtIndex:buttonIndex];
    
    if ([buttonTitle isEqualToString:@"Save to Photo"]) 
    {
        SinglePage *tempPage = [self getPageById:cur_index];
        UIComponentBase *tempLayer =  [tempPage getLayerAtIndex:0];
        
        if (tempLayer != Nil &&
            [tempLayer  isKindOfClass:[UIImageLayer class]]) 
        {
            if ([tempLayer getCurrentUIImage] != Nil) 
            {
                UIImageWriteToSavedPhotosAlbum([tempLayer getCurrentUIImage], self, nil, nil);

                [msgPanel displayMsg:@"Saving Image"];
            }

        }
    }
}

-(void) statusBarAnimationTrigger
{
    bar_status_hidden = !bar_status_hidden;
    
    if (bar_status_hidden) 
    {
        bottomBar.alpha = 0.0f;
        topBar.alpha = 0.0f;
       
        if (gDataSet.fullscreen_mode)
        {
            bottomBar.transform = CGAffineTransformMakeTranslation(0,bookXMLParser.bottomIndexPage.unit_height);
            topBar.transform = CGAffineTransformMakeTranslation(0,-50);
        }

    }
    else
    {
        bottomBar.alpha = 1.0f;
        topBar.alpha = 1.0f;
        
        if (gDataSet.fullscreen_mode)
        {
            bottomBar.transform = CGAffineTransformMakeTranslation(0, 0);
            topBar.transform = CGAffineTransformMakeTranslation(0,0);
        }
    }
}

-(void) closeCategoryLayer
{
    if (categoryLayer != Nil) 
    {
        webLayerOn = FALSE;
        [UIView transitionWithView:categoryLayer duration:0.35f 
                           options:UIViewAnimationCurveEaseOut  
                        animations:^{categoryLayer.transform = CGAffineTransformMakeTranslation(0,0);}
                        completion:NULL];
    }
}

//main scroll event
-(void) scrollViewDidScroll:(UIScrollView *)sender
{ 
    if (scroll_block_signal) 
    {
        scroll_block_signal = FALSE;
        return;
    }
    
    //check the move direction
    avg_distance += scrollView.contentOffset.x-previous_scroll_pos;
    previous_scroll_pos = scrollView.contentOffset.x;   
    
    //get the current page index
    int index = round(scrollView.contentOffset.x/scrollView.frame.size.width);
    auto_play_tick_count = 0;
    if(index >= 0 && index<page_num && cur_index != index)//&& offsetDis>0 && offsetDis<=40)
    {
        //int pre_index = cur_index;
        int predict_index = index;
        
        if(abs(avg_distance)-(page_width-100)>0)
        {
            if (avg_distance>0) 
            {
                predict_index = index+1;
                
                if (predict_index>= page_num) 
                {
                    predict_index = page_num-1;
                }
            }
            else if(avg_distance<0)
            {
                predict_index = index-1;
                
                if (predict_index<0) 
                {
                    predict_index = 0;
                }
            }
            
            if ([self checkNodeGenerated:index] == FALSE) 
            {
                cur_index = index;
                
                if ([self checkNodeInQueue:cur_index] == FALSE)
                {
                    [self updateBook:cur_index];
                }
                
                [self newPageGenAction];
                [self recycleAction];
            }
            else if(predict_index != index && [self checkNodeGenerated:predict_index] == FALSE)
            {
                cur_index = index;
                
                if ([self checkNodeInQueue:predict_index] == FALSE)
                {
                    [self updateBook:predict_index];
                }
                
                [self newPageGenAction];
                [self recycleAction];
            }
        }
        else if(abs(avg_distance)-(page_width-5)>0)
        {
            cur_index = index;
        }
        
        SinglePage *tmpPage = [self getPageById:cur_index];
        if (tmpPage != Nil) 
        {
            [tmpPage active];
        }
        
        [self updateSlideshowAutoPlay:cur_index];
    }
}

//start scroll interactive
-(void) scrollViewWillBeginDragging:(UIScrollView *)inScrollView
{
    auto_play_tick_count = 0;
    avg_distance = 0.0f;
    previous_scroll_pos = scrollView.contentOffset.x;
}

-(void) layoutAdjustWithOrientation:(UIInterfaceOrientation)interfaceOrientation
                               orientaionType:(NSString *) inOrientationType
{   
    if(topBar != Nil)
    {
       [topBar layoutAdjustWithOrientation:interfaceOrientation isFullScreen:bookXMLParser.gDataSet.fullscreen_mode];
    }
    
    if(!bookXMLParser.gDataSet.fullscreen_mode)
    {
        return;
    }
    
    CGRect screen_rect = [[UIScreen mainScreen] bounds];
    
    if(status_bar_hidden)
    {
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
    
    int status_bar_height = 0;
    if(![UIApplication sharedApplication].statusBarHidden)
    {
        status_bar_height = 20;
    }
    
    if (scrollView) 
    {
        int pre_index = cur_index;
        cur_index = round(scrollView.contentOffset.x/page_width);
       
        if(cur_index != pre_index) 
        {
            [self checkIfCurNodeNotExist];
            [self newPageGenAction];
            [self recycleAction];
            
            [self closeMediaPage];
            [self chkAndGenNewLayerAtCurIndex];
            
            [self updateSlideshowAutoPlay:cur_index];
        }
    }

    if(interfaceOrientation == UIInterfaceOrientationPortrait || 
           interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        screen_direction = 0;
        if (fit_with_screen && gDataSet.fullscreen_mode) //if fit the screen,define size data with screen size
        {
            page_width = screen_rect.size.width;
            page_height = screen_rect.size.height - status_bar_height;
        }
    }
    else if(interfaceOrientation == UIInterfaceOrientationLandscapeRight || 
            interfaceOrientation == UIInterfaceOrientationLandscapeLeft)
    {
        screen_direction = 1;
        if (fit_with_screen && gDataSet.fullscreen_mode) //if fit the screen,define size data with screen size
        {
            page_width = screen_rect.size.height;
            page_height = screen_rect.size.width - status_bar_height;
        }
    }
    
    self.frame = CGRectMake(0,0, page_width, page_height);
    bgView.frame = CGRectMake(0,0, page_width, page_height);
    
    if (scrollView != Nil) 
    {
        scroll_block_signal = TRUE;
        scrollView.frame =  CGRectMake(0,0,page_width, page_height);
        scrollView.contentSize = CGSizeMake(page_num*page_width,page_height);
        
        if (cur_index>=0 && cur_index<page_num) 
        {
            scrollView.contentOffset = CGPointMake(cur_index*page_width,0);
        }
    }
    
    if(bottomBar != Nil)
    {
        if (bar_status_hidden) 
        {
            bottomBar.frame = CGRectMake(0,page_height,
                                         page_width,bottomBar.frame.size.height);     
        }
        else
        {
            bottomBar.frame = CGRectMake(0,page_height-bookXMLParser.bottomIndexPage.unit_height,
                                         page_width,bottomBar.frame.size.height);            
        }        
        
        [bottomBar layoutAdjustWithOrientation:interfaceOrientation];
    }
    
    if(webLayer != Nil)
    {
        if(webLayerOn)
        {
            webLayer.transform = CGAffineTransformMakeTranslation(0,0);
            webLayer.frame = CGRectMake(0, page_height,page_width,page_height);
            webLayer.transform = CGAffineTransformMakeTranslation(0,-page_height);
        }
        else
        {
            webLayer.transform = CGAffineTransformMakeTranslation(0,0);
            webLayer.frame = CGRectMake(0,page_height,page_width,page_height);
            webLayer.alpha = 0;
        }
        [webLayer layoutAdjustWithOrientation:interfaceOrientation];
    }
    
    if (categoryLayer != Nil)
    {
        if(categoryOn)
        {
            categoryLayer.transform = CGAffineTransformMakeTranslation(0,0);
            categoryLayer.frame = CGRectMake(0, page_height+topBar.frame.size.height,page_width,page_height);
            categoryLayer.transform = CGAffineTransformMakeTranslation(0,-page_height);
        }
        else
        {
            categoryLayer.transform = CGAffineTransformMakeTranslation(0,0);
            categoryLayer.frame = CGRectMake(0,page_height+topBar.frame.size.height,page_width,page_height);
            categoryLayer.alpha = 0;
        }
        [categoryLayer layoutAdjustWithOrientation:interfaceOrientation];
    }
    
    if (msgPanel != Nil) 
    {
        msgPanel.frame = CGRectMake((page_width-msgPanel.frame.size.width)/2,
                                        (page_height-msgPanel.frame.size.height)/2, 
                                        msgPanel.frame.size.width, 
                                        msgPanel.frame.size.height);
    }
    
    if ([inOrientationType isEqualToString:@"g"] && fit_with_screen == 1) 
    {
        //READJUST THE PAGE POSITION
        for (SinglePage* page in pages) 
        {
            if (page.resizeMode == 0 && !(gDataSet.landscape_two_page && [curOrientationView isEqualToString:@"h"])) //bottom layer auto resizing
            {
                UIComponentBase *tmpLayer = [page getLayerAtIndex:0];
                
                if (tmpLayer != Nil && 
                    ([tmpLayer.type isEqualToString:@"IMAGE_LAYER"] || 
                     [tmpLayer.type isEqualToString:@"VIDEO_PLAYER"]))
                {
                    [tmpLayer layoutAdjustWithOrientation:interfaceOrientation];
                }                
            }

            if(gDataSet.landscape_two_page && [curOrientationView isEqualToString:@"h"])
            {
               page.frame = CGRectMake(page.page_id*page_width/2, 0, page_width/2, page_height);
            }
            else
                page.frame = CGRectMake(page.page_id*page_width, 0, page_width, page_height);
            
            [page layoutAdjustWithOrientation:interfaceOrientation isLandScapeTwoPage:gDataSet.landscape_two_page isInit:FALSE];
        }
    }

}

//reset,clean up the media book 
-(void) reset
{
    self.userInteractionEnabled = false;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    if(objQueMagTimer)
    {
        [objQueMagTimer invalidate];
        objQueMagTimer = Nil;
    }
    
    if(recycleSet)
    {
        //release the unused page
        for (SinglePage* page in recycleSet ) 
        {
            //[recycleSet removeObject:page];
            [pages removeObject:page];
            
            if(page && [page superview] != Nil)
            {
                [page reset];
                [page removeFromSuperview];
                [page release];
            }
        }
        
        [recycleSet removeAllObjects];
        [recycleSet release];
    }
    
    for (SinglePage* page in pages) 
    {
        if(page && [page superview] != Nil)
        {
            [page reset];
            [page removeFromSuperview];
            [page release];
        }
    }
   
    [topBar reset];
    [topBar removeFromSuperview];
    [topBar release];
    
    [bottomBar reset];
    [bottomBar removeFromSuperview];
    [bottomBar release];
    
    [genNodeQueue removeAllObjects];
    [genNodeQueue release];

    [pages removeAllObjects];
    [pages release];
    
    [tempMediaSet removeAllObjects];
    [tempMediaSet release];
    
    [backGroundImage removeFromSuperview];
    [backGroundImage reset];
    [backGroundImage release];
    
    scrollView.delegate = Nil;
    [scrollView removeFromSuperview];
    [scrollView release];
    
    [webLayer removeFromSuperview];
    [webLayer release];

    [categoryLayer removeFromSuperview];
    [categoryLayer reset];
    [categoryLayer release];
  
    [bookXMLParser reset];
    [albumXMLParser reset];
    
    if(bgView)
    {
        [bgView release];
        [bgView removeFromSuperview];
    }
    
    if(activityIndicator)
    {
        [activityIndicator release];
        [activityIndicator removeFromSuperview];
    }
    
    for (UIView*singleView in[self subviews]) 
    {
        [singleView removeFromSuperview];
    }

}

- (void)dealloc
{
    [super dealloc];
}

@end
